package com.txy.springcloud.service.dubbo;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.txy.springcloud.service.dubbo.CodeService;
import com.txy.springcloud.service.dubbo.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService {


    @Autowired
    private ComboPooledDataSource dataSource;

    @Reference
    private EmailService emailService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean create(String email) {
        // 生成验证码
        String code = create();
        // 存数据库
        saveCode(email, code);
        // 发送邮箱
        return emailService.sendCode(email, code);

    }

    @Override
    public int validate(String email, String code) {
        return 0;
    }

    private static final Random random = new Random();

    private static final Integer END = 10;

    private static final Integer CAPTCHA_LENGTH = 6;//验证码长度，nextDouble()方法生成的数字精确到小数点后16位，所以验证码长度最大可以到16位。

    private String create() {
        Double pross = random.nextDouble() * Math.pow(END, CAPTCHA_LENGTH);
        String captcha = String.format("%06.0f", pross);
        return captcha;
    }

    private void saveCode(String email, String code) {
        try {
            PreparedStatement preparedStatement = dataSource.getConnection().prepareStatement("insert into verification_code(email, `value`) values (?, ?) ON DUPLICATE KEY UPDATE `value`= ?, createTime = now()");
            preparedStatement.setString(1, email);
            preparedStatement.setString(2, code);
            preparedStatement.setString(3, code);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
